<script lang="ts" setup>
import {
  ElMessageBox,
  ElDialog,
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElRadioGroup,
  ElRadio,
  ElMessage,
  ElTreeSelect,
} from "element-plus";
import { nextTick, reactive, ref } from "vue";
import {
  add,
  edit,
  getOrganizationById,
  getOrganizationsByUserId,
} from "#/api/sys/organization";

const dialogVisible = ref(false);
const title = ref("添加组织");
const defaultProps = {
  children: "children",
  label: "organizationName",
};

const spaceInput = (field: string, value: string) => {
  // 过滤空格
  ruleForm[field] = value.replace(/\s+/g, "");
};

const useForm = () => {
  const formRef = ref();
  const reset = async () => {
    await nextTick();
    formRef.value?.resetFields();
  };
  return { formRef, reset };
};
const { formRef: ruleFormRef, reset } = useForm();

const addDialog = () => {
  dialogVisible.value = true;
  title.value = "添加组织";
  reset();
  getTableData();
};

const editDialog = (obj) => {
  dialogVisible.value = true;
  title.value = "编辑组织";
  ruleForm.id = obj.id;
  getDetail(obj.id);
  getTableData(obj.id); // 传递当前组织ID
  ruleForm.children = obj.children;
  ruleForm.level = obj.level;
};

defineExpose({ addDialog, editDialog });
const emit = defineEmits(["search"]);

const ruleForm = reactive<RuleForm>({
  id: "",
  parentId: "",
  organizationName: "",
  chargeName: "",
  sort: 1,
  status: "true",
  children: [],
  level: 1,
});

const rules = reactive({
  parentId: [{ required: true, message: "请选择组织名称", trigger: "change" }],
  organizationName: [
    { required: true, message: "请输入组织名称", trigger: "blur" },
    { min: 1, max: 20, message: "请输入最多20字", trigger: "blur" },
  ],
  sort: [{ required: true, message: "请输入排序号", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
  chargeName: [{ min: 1, max: 20, message: "请输入最多20字", trigger: "blur" }],
});
const treeData = ref([]);

const loading = ref(false);

const getDetail = async (id) => {
  const params = {
    id: id,
  };
  const { data } = await getOrganizationById(params);
  ruleForm.organizationName = data.organizationName;
  ruleForm.parentId = data.parentId;
  ruleForm.status = data.status + "";
  ruleForm.sort = data.sort;
  ruleForm.chargeName = data.chargeName;
};

const addForm = () => handleSubmit(false);
const editForm = () => handleSubmit(true);

const buildFormParams = (isEdit: boolean) => ({
  ...(isEdit && { id: ruleForm.id }),
  parentId: ruleForm.parentId,
  status: ruleForm.status,
  organizationName: ruleForm.organizationName,
  sort: ruleForm.sort,
  chargeName: ruleForm.chargeName,
  ...(isEdit && { parentId: ruleForm.parentId }),
});

const handleApiResponse = (isEdit: boolean) => {
  ElMessage.success(isEdit ? "修改成功" : "添加成功");
  emit("search");
  dialogVisible.value = false;
};

const submitForm = async (isEdit = false) => {
  if (loading.value) return;

  try {
    loading.value = true;
    await ruleFormRef.value?.validate();

    const params = buildFormParams(isEdit);
    const { code, msg } = isEdit ? await edit(params) : await add(params);

    if (code === 200) handleApiResponse(isEdit);
    else ElMessage.error(msg);
  } catch (error) {
    ElMessage.error("表单验证失败，请检查输入内容");
  } finally {
    loading.value = false;
  }
};

const resetForm = () => {
  if (!ruleFormRef) return;
  ruleFormRef.value.resetFields();
  dialogVisible.value = false;
};

const handleClose = (done: () => void) => {
  dialogVisible.value = false;
};

const getTableData = async (currentOrgId = null) => {
  const data = await getOrganizationsByUserId();

  const addLevelToTreeData = (nodes: any[], level = 1) => {
    return nodes.map((node) => {
      const nodeWithLevel = {
        ...node,
        level: level,
      };

      if (nodeWithLevel.children && nodeWithLevel.children.length > 0) {
        nodeWithLevel.children = addLevelToTreeData(
          nodeWithLevel.children,
          level + 1
        );
      }

      return nodeWithLevel;
    });
  };

  const processDisabledNodes = (nodes: any[]) => {
    return nodes.map((node) => {
      const processedNode = { ...node };

      // 在编辑状态下，禁用当前组织节点
      if (currentOrgId && node.id === currentOrgId) {
        processedNode.disabled = true;
      }

      // 原有的层级禁用逻辑
      if (node.level >= 3) {
        processedNode.disabled = true;
      }

      // 如果有子节点，递归处理子节点
      if (processedNode.children && processedNode.children.length > 0) {
        processedNode.children = processDisabledNodes(processedNode.children);
      }

      return processedNode;
    });
  };

  const dataWithLevel = addLevelToTreeData(data.data);
  treeData.value = processDisabledNodes(dataWithLevel);
};
</script>

<template>
  <div class="page">
    <ElDialog
      v-model="dialogVisible"
      :title="title"
      width="600"
      :before-close="handleClose"
    >
      <div>
        <ElForm
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
        >
          <ElFormItem label="上级组织：" prop="parentId">
            <ElTreeSelect
              v-model="ruleForm.parentId"
              :data="treeData"
              node-key="id"
              :props="defaultProps"
              :render-after-expand="false"
              check-strictly
              placeholder="请选择上级组织"
              style="width: 420px"
              :disabled="ruleForm.level == 2 && ruleForm.children.length > 0"
            />
          </ElFormItem>
          <ElFormItem label="组织名称：" prop="organizationName">
            <ElInput
              v-model="ruleForm.organizationName"
              placeholder="请输入组织名称"
              style="width: 420px"
              @input="(value) => spaceInput('organizationName', value)"
            />
          </ElFormItem>
          <ElFormItem label="排序：" prop="sort">
            <ElInputNumber
              v-model="ruleForm.sort"
              :min="1"
              :max="9999"
              controls-position="right"
              size="large"
              placeholder="请输入排序号"
              style="width: 420px"
            />
          </ElFormItem>
          <ElFormItem label="负责人：" prop="chargeName">
            <ElInput
              v-model="ruleForm.chargeName"
              placeholder="请输入负责人姓名"
              style="width: 420px"
              @input="(value) => spaceInput('chargeName', value)"
            />
          </ElFormItem>
          <ElFormItem label="状态：" prop="status">
            <ElRadioGroup v-model="ruleForm.status" placeholder="请选择状态">
              <ElRadio value="true">启用</ElRadio>
              <ElRadio value="false">禁用</ElRadio>
            </ElRadioGroup>
          </ElFormItem>
        </ElForm>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="resetForm" :disabled="loading">取消</ElButton>
          <ElButton
            type="primary"
            @click="() => submitForm(title !== '添加组织')"
            :loading="loading"
          >
            确定
          </ElButton>
        </div>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped>
:deep(.el-input-number .el-input__inner) {
  text-align: left !important;
}
</style>